import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  Typography, 
  message, 
  FormProps,
  Alert
} from 'antd';
import { 
  UserOutlined, 
  LockOutlined, 
} from '@ant-design/icons';
import './index.css';
import { useAuth } from '../../contexts/AuthContext';
import { getMacAddress } from '../../utils/request';

const { Title, Text } = Typography;

// 定义表单值类型
interface LoginFormValues {
  username: string;
  password: string;
  remember: boolean;
}

const LoginPage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [macAddress, setMacAddress] = useState<string | null>(null);
  const [macLoading, setMacLoading] = useState<boolean>(true);
  const [form] = Form.useForm<LoginFormValues>();
  const { login } = useAuth();

  // 获取MAC地址
  useEffect(() => {
    const fetchMacAddress = async () => {
      try {
        const mac = await getMacAddress();
        setMacAddress(mac);
      } catch (error) {
        console.error('获取MAC地址失败:', error);
      } finally {
        setMacLoading(false);
      }
    };

    fetchMacAddress();
  }, []);

  const onFinish: FormProps<LoginFormValues>['onFinish'] = async (values) => {
    setLoading(true);
    try {
      const { username, password } = values;
      await login(username, password);
    } catch (error) {
      const err = error instanceof Error ? error : new Error('登录失败');
      message.error(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <Card className="login-card" hoverable>
        <div className="login-header">
          <Title level={3} className="login-title">系统登录</Title>
          <Text type="secondary">欢迎使用，请登录您的账号</Text>
        </div>

        {/* 开发环境下显示MAC地址信息 */}
        {process.env.NODE_ENV === 'development' && (
          <Alert
            message="设备信息"
            description={
              macLoading ? (
                <Text>正在获取设备MAC地址...</Text>
              ) : macAddress ? (
                <Text>MAC地址: <Text code>{macAddress}</Text></Text>
              ) : (
                <Text type="warning">无法获取MAC地址</Text>
              )
            }
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        <Form<LoginFormValues>
          form={form}
          name="login"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item<LoginFormValues['username']>
            name="username"
            rules={[
              { required: true, message: '请输入用户名!' },
              { min: 4, message: '用户名至少4个字符' },
              { 
                pattern: /^[a-zA-Z0-9_]+$/,
                message: '用户名只能包含字母、数字和下划线' 
              }
            ]}
          >
            <Input 
              prefix={<UserOutlined />} 
              placeholder="用户名" 
              size="large" 
            />
          </Form.Item>

          <Form.Item<LoginFormValues['password']>
            name="password"
            rules={[
              { required: true, message: '请输入密码!' },
              { min: 6, message: '密码至少6个字符' },
              {
                validator: (_, value) => {
                  if (value && value.includes(' ')) {
                    return Promise.reject('密码不能包含空格');
                  }
                  return Promise.resolve();
                }
              }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              size="large"
            />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              block 
              size="large"
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
        </Form>

      </Card>
    </div>
  );
};

export default LoginPage;